﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace mapleHttpTestServer.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FilesystemController : ControllerBase
    {

        // GET api/<FishController>/5
        [HttpHead("{name}")]
        [HttpGet("{name}")]
        public IActionResult Get(string name)
        {
            //支持部分获取

                string upfilePath = Path.Combine(Directory.GetCurrentDirectory(), "files", name);
                if (System.IO.File.Exists(upfilePath))
                {
                    return new FileStreamResult(new FileStream(upfilePath, FileMode.Open, FileAccess.Read, FileShare.Read), "application/octet-stream")
                    {
                        FileDownloadName = name,
                        EnableRangeProcessing = true
                    };
                }
            return NotFound();
        }


        [HttpPost]
        public async Task<bool> Post([FromQuery]string name)
        {
            if (string.IsNullOrEmpty(name))
                return false;

            return await saveStreamToFile(Request.Body, name);
        }

        [HttpPost, Route("UploadForm")]
        public async Task<bool> UploadForm([FromForm] IFormCollection formcollection)
        {
            if (formcollection == null || formcollection.Files == null)
                return false;

            bool result = true;

            foreach (IFormFile file in formcollection.Files)
            {
                result = result && await saveFile(file);
            }

            return result;
        }

        [HttpPost, Route("UploadFormModel")]
        public async Task<bool> UploadFormModel([FromForm] UpFileModel model)
        {
            if (model == null || model.FormCollection == null || model.FormCollection.Files == null)
                return false;

            if (string.IsNullOrEmpty(model.Message))
                return false;

            bool result = true;

            foreach (IFormFile file in model.FormCollection.Files)
            {
                result = result && await saveFile(file);
            }

            return result;
        }

        private async Task<bool> saveFile(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return false;

            //string fileOrginname = file.FileName;//原始的文件名称
            //string contentType = file.ContentType;
            string name = file.Name;
            //string fileExtention = Path.GetExtension(fileOrginname);

            return await saveStreamToFile(file.OpenReadStream(), name);
        }

        private async Task<bool> saveStreamToFile(Stream stream, string fileName)
        {
            bool result = false;

            try
            {
                string fileDir = Path.Combine(Directory.GetCurrentDirectory(), "files");
                if (!System.IO.Directory.Exists(fileDir))
                    System.IO.Directory.CreateDirectory(fileDir);

                string upfilePath = Path.Combine(fileDir, fileName);

                using (FileStream fileStream = new FileStream(upfilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    await stream.CopyToAsync(fileStream);
                }

                result = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("FilesystemController Save Stream To File Error . " + ex.Message);
            }


            return result;
        }
    }

    public class UpFileModel
    {
        public string Message { get; set; }
        public string Message2 { get; set; }
        public IFormCollection FormCollection { get; set; }
    }
}
